package com.paireach.bw.activity;


import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.utils.FileUtils;
import com.bumptech.glide.Glide;
import com.liji.takephoto.TakePhoto;
import com.nanchen.compresshelper.CompressHelper;
import com.paireach.bw.R;
import com.paireach.bw.base.BaseActivity;
import com.paireach.bw.event.HttpErrorEvent;
import com.paireach.bw.event.HttpSuccessEvent;
import com.paireach.bw.http.RequestTag;
import com.paireach.bw.http.UserRequest;
import com.paireach.bw.utils.LogUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;

import de.hdodenhof.circleimageview.CircleImageView;
import es.dmoral.toasty.Toasty;
import okhttp3.Call;

/**
 * Created by ${cqc} on 2017/2/6.
 */

public class ModifyPersonalActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "ModifyPersonalActivity";
    private Toolbar toolbar;
    private TextView tv_cph;
    private RelativeLayout rl1;
    private RelativeLayout rl2;
    private RelativeLayout rl3;
    private RelativeLayout rl4;
    private CircleImageView iv_avatar;
    private Button btn_commit;
    private Context context;
    private TextView tv_car_type;
    private TextView tv_phone;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
            Transition slide_bottom = TransitionInflater.from(this).inflateTransition(android.R.transition.slide_bottom);
            getWindow().setEnterTransition(slide_bottom);
        }
        setContentView(R.layout.activity_modify_personal_options);
        context = this;
        findViews();
        initViews();
    }

    private void initViews() {
        initToolbar();
        rl1.setOnClickListener(this);
        rl2.setOnClickListener(this);
        rl3.setOnClickListener(this);
        rl4.setOnClickListener(this);
        btn_commit.setOnClickListener(this);

        String path = getApplicationContext().getFilesDir().getAbsolutePath() + "/avatar.png";
        File avatarFile = new File(path);
        if (avatarFile.exists()) {
            Glide.with(context).load(avatarFile).into(iv_avatar);  //load("file://" + path)
        }else{
            //TODO
            Glide.with(context).load("url").into(iv_avatar);
        }
    }

    private void initToolbar() {
        toolbar.setNavigationIcon(R.mipmap.back);
        toolbar.setTitle("修改个人信息");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
    }

    private void findViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        tv_cph = (TextView) findViewById(R.id.tv_cph);
        rl1 = (RelativeLayout) findViewById(R.id.rl1);
        rl2 = (RelativeLayout) findViewById(R.id.rl2);
        rl3 = (RelativeLayout) findViewById(R.id.rl3);
        rl4 = (RelativeLayout) findViewById(R.id.rl4);
        iv_avatar = (CircleImageView) findViewById(R.id.iv_avatar);
        tv_car_type = (TextView) findViewById(R.id.tv_car_type);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        btn_commit = (Button) findViewById(R.id.btn_commit);

        progressBar = (ProgressBar) findViewById(R.id.progressBar);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl1:
                showPhoto();//头像
                break;
            case R.id.rl2://车型
                showDialog("车型", tv_car_type);
                break;
            case R.id.rl3://车牌号
                showDialog("车牌号", tv_cph);
                break;
            case R.id.rl4://手机号
                showDialog("手机号", tv_phone);
                break;
            case R.id.btn_commit:
                //提交个人信息
//                showProgressDialog();
                progressBar.setVisibility(View.VISIBLE);
                new UserRequest().commitUserInfo("", "");
                break;
        }
    }

    @Override
    public void httpSuccessEvent(HttpSuccessEvent event) {
        super.httpSuccessEvent(event);
        if (event.getRequestTag() == RequestTag.COMMIT_USER_INFO) {
            dismissProgressDialog();
            // TODO: 2017/2/7
//            Toasty.info(context,event.getJson()).show();
        }
    }

    @Override
    public void httpErrorEvent(HttpErrorEvent event) {
        super.httpErrorEvent(event);
        if (event.getRequestTag() == RequestTag.COMMIT_USER_INFO) {
            dismissProgressDialog();
//            Toasty.warning(context, event.getErrorMessage()).show();
            showWarning(event.getErrorMessage());
        }
    }

    private void showDialog(String title, final TextView tv) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View view = View.inflate(context, R.layout.dialog_price_et, null);
        final EditText et = (EditText) view.findViewById(R.id.et_price);
        builder.setTitle(title)
                .setView(view)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String text = et.getText().toString().trim();
                        tv.setText(text);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
        builder.create().show();
    }

    private void showPhoto() {
        TakePhoto takePhoto = new TakePhoto(ModifyPersonalActivity.this);
        takePhoto.setOnPictureSelected(new TakePhoto.onPictureSelected() {
            @Override
            public void select(String path) {
                //获取当前程序路径  /data/data/com.paireach.bw/files
                String path1 = getApplicationContext().getFilesDir().getAbsolutePath() + "/avatar.png";
                boolean isCopySuccess = FileUtils.copyFile(path, path1);
                if (isCopySuccess) {
                    Glide.with(ModifyPersonalActivity.this).load("file://" + path).into(iv_avatar);
                    File oldFile = new File(path1);
                    //todo  上传头像图片
                    //默认压缩，图片还是有点大，一般拍照的图片压缩 后在50-150KB之间
                    //File newFile = CompressHelper.getDefault(getActivity()).compressToFile(oldFile);
                    //自定义压缩
                    File newFile = new CompressHelper.Builder(ModifyPersonalActivity.this)
                            .setMaxWidth(200)  // 默认最大宽度为720/8=90
                            .setMaxHeight(300) // 默认最大高度为960/8=120
                            .setQuality(50)    // 默认压缩质量为80
                            .setCompressFormat(Bitmap.CompressFormat.JPEG) // 设置默认压缩为jpg格式
//                            .setFileName(oldFile.getName()) // 设置你的文件名
                            // .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath())//API>22时压缩失败，所以注释掉
                            .build()
                            .compressToFile(oldFile);
                    if (newFile == null) {
                        newFile = oldFile;
                    }
                    OkHttpUtils.postFile()
                            .url("")
                            .file(newFile)
                            .build()
                            .execute(new MyStringCallback());
                }
            }
        });
        takePhoto.show();
    }


    public class MyStringCallback extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {
            e.printStackTrace();
            LogUtil.d(TAG, "onError");
            showToast("图片上传失败");
        }

        @Override
        public void onResponse(String response, int id) {
            LogUtil.d(TAG, "onResponse");

            switch (id) {
                case 100:
                    showToast("图片上传成功");
                    break;
                case 101:
//                    Toast.makeText(context, "https", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }
}
